layui.define(function (exports) {
    var $      = layui.$,
        setter = layui.setter,
        admin  = layui.admin;
    $.ajaxSetup({
        headers    : {
            "Access-Token": layui.data(setter.tableName).access_token,
            //            "Set-Cookie"  : document.cookie,
        },
        xhrFields  : {
            withCredentials: true // 这里设置了withCredentials
        },
        crossDomain: true
    });
    let helper = {
        request     : function (url, type, data, callback) {
            $.ajax({
                type    : type,
                url     : setter.requestUrl + url,
                data    : data,
                dataType: 'json',
                success : (res) => {
                    helper.closeLoading();
                    if (res.code == setter.response.statusCode.logout) {
                        admin.exit();
                        return;
                    }
                    if ((undefined !== res.length && res.length > 0) || res.code == 0) {
                        callback(res);
                        return;
                    }
                    if (res.code == 403) {
                        layer.alert('您的权限不足', function () {
                            window.history.back();
                            return true;
                        })
                        return;
                    }
                    if (window.errorAlertType === undefined || !window.errorAlertType){
                        this.error(res.msg);
                        return;
                    }
                    layer.alert(res.msg);
                    return;
                },
                error   : function (e) {
                    helper.closeLoading();
                    console.log(e);
                }
            });
        },
        post        : function (url, data, callback) {
            this.request(url, 'post', data, callback)
        },
        get         : function (url, callback) {
            this.request(url, 'get', {}, callback)
        },
        success     : function (msg, callback) {
            layer.msg(msg, {
                time: 1500,
                end : function () {
                    if (callback) callback();
                }
            })
        },
        error       : function (msg, callback) {
            layer.msg(msg, {
                time: 1500,
                icon: 2,
                end : function () {
                    if (callback) callback();
                }
            })
        },
        loading     : function (msg) {
            var index = layer.load(1, {
                time: false,
            });
        },
        closeLoading: function () {
            layer.closeAll('loading')
        },
        /**
         * 模拟PHP sprintf 的函数
         * @returns string
         */
        sprintf     : function () {
            let args = arguments, string = args[0];
            for (let i = 1; i < args.length; i++) {
                let item = arguments[i];
                string   = string.replace('%d', item);
            }
            return string;
        },
        /**
         * 获取完整的时间格式
         * @param time
         * @returns {string}
         */
        getFullDate(time) {
            var month = time.getMonth() + 1, day = time.getDate();
            if (month < 10) {
                month = "0" + month;
            }
            if (day < 10) {
                day = "0" + day;
            }
            return time.getFullYear() + '-' + month + '-' + day;
        } ,
        /**
         * 上传渲染
         * @param id
         * @param url
         * @param callback
         */
        uploadRender(id , url , callback){
            layui.upload.render({
                elem: id
                , url: url //改成您自己的上传接口
                , done: function (res) {
                    //如果上传失败
                    if (res.code > 0) {
                        return layer.msg(res.msg);
                    }
                    callback(res);
                }
                , error: function (res) {
                    helper.error('上传失败');
                }
            });
        } ,
        /**
         * 弹窗式视图
         * @param title 标题
         * @param area 大小 ['100px','200px']
         * @param template 模板文件位置
         * @param postUrl 保存提交地址
         * @param data 要保存的数据
         */
        popView(title , area , template , postUrl , data){
            admin.popup({
                title    : title
                , area   : area
                , id     : 'LAY-popup-content-comm'
                , success: function (layero, index) {
                    if (data) window.params = data;
                    layui.view(this.id).render(template).done(function () {
                        layui.form.render(null, 'layuiadmin-form');
                        //监听提交
                        layui.form.on('submit(layuiadmin-submit)', function (res) {
                            var field = res.field; //获取提交的字段
                            helper.post(postUrl, field, function (res) {
                                helper.success(res.msg, function () {
                                    layui.table.reload('layuiadmin-table'); //重载表格
                                    layer.close(index); //执行关闭
                                });
                            })
                        });
                    });
                }
            });
        } ,
        /**
         * 确认
         * @param title
         * @param postUrl
         * @param id
         * @param callback
         */
        confirmReload(title , postUrl , id , callback){
            let params = {};
            if (typeof id == 'object'){
                params = id;
            }else{
                params.id = id;
            }
            if (!callback) callback = function(){layui.table.reload('layuiadmin-table');}
            layer.confirm(title, function (index) {
                helper.post(postUrl, params, function (res) {
                    callback();
                    layer.msg(res.msg||'删除成功');
                    layer.close(index);
                });
            });
        } ,
        /**
         * 确认
         * @param title
         * @param callback
         */
        confirm(title , callback){
            if (!callback) callback = function(){}
            layer.confirm(title, function (index) {
                layer.close(index);
                callback();
            });
        } ,
        /**
         * 请求后渲染下拉框
         * @param url
         * @param selectName
         * @param className
         * @param form
         * @param options
         */
        requestRenderSelect(url , selectName , className , form , options){
            if (!options) options = {};
            let self = this;
            helper.get(url, function (res) {
                self.renderSelect(res.data , selectName , className , options);
                if (form) form.render('select');
            })
        } ,
        /**
         * 渲染表单
         * @param data
         * @param selectName
         * @param className
         * @param options
         */
        renderSelect(data , selectName , className , options){
            let optionSelect = options.filter ? "lay-filter='" + options.filter + "' " : '';
            let html = '<select name="' + selectName + '" class="layui-select" ' + optionSelect + '>';
            data.forEach((item) => {
                let selected = item.selected ? 'selected' : '';
                html += '<option value="' + item.id + '" ' + selected + '>' + item.name + '</option>';
            })
            html += '</select>';
            $(className).html(html);
        }
    }
    exports('helper', helper)
})